from datetime import datetime

from pydantic import BaseModel
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.orm import declarative_base
from sqlalchemy.future import select

from utils.drivers.database.engine import AsyncSession
from utils.exception import AppException, StatusCode

Base = declarative_base()


class SiteInfoModel(BaseModel):
    name: str
    keyword: str
    description: str
    tel: str
    email: str
    fax: str
    contact_person: str
    phone: str
    qq: str
    longitude: str
    latitude: str
    address: str
    record_number: str

class SlideshowModel(BaseModel):
    id: int
    sort: int


class Params(Base):
    __tablename__ = "params"

    id = Column(Integer, primary_key=True, autoincrement=True)
    key = Column(String(255))
    value = Column(String)
    type = Column(String(255))
    create_time = Column(DateTime, default=datetime.now())
    update_time = Column(DateTime, default=datetime.now(), onupdate=datetime.now())

    @classmethod
    async def get_site_info(cls) -> (SiteInfoModel, SiteInfoModel):
        """
        获取站点信息设置
        """
        try:
            async with AsyncSession() as session:
                async with session.begin():
                    site_info = await session.execute(select(cls).where(cls.type == "site_info"))
                    site_info = {str(p.key): str(p.value) for p in site_info.scalars().all()}
        except Exception as e:
            raise AppException(StatusCode.QuerySideInfoError, detail=str(e))

        site_info_cn = SiteInfoModel(
            name=site_info.get("cn_site_name"),
            keyword=site_info.get("cn_site_keyword"),
            description=site_info.get("cn_site_description"),
            tel=site_info.get("tel"),
            email=site_info.get("email"),
            fax=site_info.get("fax"),
            contact_person=site_info.get("cn_contact_person"),
            phone=site_info.get("phone"),
            qq=site_info.get("qq"),
            longitude=site_info.get("longitude"),
            latitude=site_info.get("latitude"),
            address=site_info.get("cn_address"),
            record_number=site_info.get("record_number")
        )

        site_info_en = SiteInfoModel(
            name=site_info.get("en_site_name"),
            keyword=site_info.get("en_site_keyword"),
            description=site_info.get("en_site_description"),
            tel=site_info.get("tel"),
            email=site_info.get("email"),
            fax=site_info.get("fax"),
            contact_person=site_info.get("en_contact_person"),
            phone=site_info.get("phone"),
            qq=site_info.get("qq"),
            longitude=site_info.get("longitude"),
            latitude=site_info.get("latitude"),
            address=site_info.get("en_address"),
            record_number=site_info.get("record_number")
        )

        return site_info_cn, site_info_en

    @classmethod
    async def get_slideshow(cls) -> list[dict]:
        """
        获取轮播图
        """
        try:
            async with AsyncSession() as session:
                async with session.begin():
                    slideshow = await session.execute(select(cls).where(cls.type == "slideshow"))
                    slideshow = slideshow.scalars().all()
                    if not slideshow:
                        slideshow = []
                    slideshow = [SlideshowModel(id=s.id, sort=int(s.value)) for s in slideshow]
                    slideshow.sort(key=lambda x: x.sort)
                    return slideshow
        except Exception as e:
            raise AppException(StatusCode.QuerySlideshowError, detail=str(e))
